package com.zziq.cloudpicturebank.job.once;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.zziq.cloudpicturebank.constant.RabbitMqConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 用于创建测试程序用到的交换机和队列（只用在程序启动前执行一次）
 */
@Slf4j
@Component
//@Order(1)

public class MqInitMain {
    @Autowired
    private ConnectionFactory connectionFactory;

    @PostConstruct
    @Bean
    public void init() {
        try (Connection connection = connectionFactory.newConnection();
             Channel channel = connection.createChannel()){
            String EXCHANGE_NAME = RabbitMqConstant.CALCULATE_PICCOLOR_EXCHANGE;
            channel.exchangeDeclare(EXCHANGE_NAME, "direct");

            // 创建队列，随机分配一个队列名称
            String queueName = RabbitMqConstant.CALCULATE_PICCOLOR_QUEUE;
            channel.queueDeclare(queueName, true, false, false, null);
            channel.queueBind(queueName, EXCHANGE_NAME, RabbitMqConstant.CALCULATE_PICCOLOR_ROUTING_KEY);
            log.info("消息队列启动成功");
        } catch (Exception e) {
            log.error("消息队列启动失败，异常：{}", e.getMessage());
        }

    }
}
